package com.chii.auth.service.impl;


import com.chii.auth.client.UserClient;
import com.chii.auth.po.Role;
import com.chii.auth.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserClient userClient;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名 查询密码
        User user = userClient.getUserByUsernameFromUser(username).getData();
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<Role> roles = userClient.getRoleByUserIdFromUser(user.getId()).getData();
        if (roles != null && roles.size() > 0) {
            roles.forEach(role -> {
                //存放role name  或者 权限名字
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            });
        }

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getEnabled(),
                user.getNotExpired(),
                user.getCredentialsNotExpired(),
                user.getAccountNotLocked(),
                grantedAuthorities);
    }
}
